package graphics.screens.mode;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import javax.microedition.io.Connector;
import javax.microedition.io.file.FileConnection;

import state.State;

import boot.Boot;
import files.Files;

public class PlayModeSaver {

	public static final String FILE_PATH = Files.BOOT_ROOT
			+ "/Navigator/mode.db";

	public void save(String mode) {
		try {
			FileConnection fc = (FileConnection) Connector.open(FILE_PATH);
			if (fc.exists()) {
				fc.delete();
			}
			fc.create();

			OutputStream fos = fc.openOutputStream();
			fos.write(((mode).getBytes()));
			fos.close();

			fc.close();
		} catch (IOException e) {
			Boot.alertException(e, this, "save()");
		}
	}

	public void switchState() {
		if (Boot.state().equals(State.NO_REPEAT_NO_PLAYLIST)) {
			Boot.state().remove(State.NO_REPEAT_NO_PLAYLIST);
			Boot.state().add(State.REPEAT_ONE_TUNE);
			save("REPEAT_ONE_TUNE");
		} else if (Boot.state().equals(State.REPEAT_ONE_TUNE)) {
			Boot.state().remove(State.REPEAT_ONE_TUNE);
			Boot.state().add(State.PLAYLIST_MODE);
			save("PLAYLIST_MODE");
		} else if (Boot.state().equals(State.PLAYLIST_MODE)) {
			Boot.state().remove(State.PLAYLIST_MODE);
			Boot.state().add(State.NO_REPEAT_NO_PLAYLIST);
			save("NO_REPEAT_NO_PLAYLIST");
		}
	}

	public void reload() {
		String result = null;
		int bufferLength = 512;
		byte[] b = new byte[bufferLength];
		try {
			FileConnection fc = (FileConnection) Connector.open(FILE_PATH);

			if (!fc.exists()) {
				throw new IOException("File does not exists");
			}
			InputStream fis = fc.openInputStream();
			int length = fis.read(b, 0, bufferLength);

			result = new String(b, 0, length);
			fis.close();
			fc.close();
		} catch (IOException e) {
			Boot.alertException(e, this, "reload()");
		}

		if ("REPEAT_ONE_TUNE".equals(result)) {
			Boot.state().remove(State.NO_REPEAT_NO_PLAYLIST);
			Boot.state().remove(State.PLAYLIST_MODE);
			Boot.state().add(State.REPEAT_ONE_TUNE);
		} else if ("PLAYLIST_MODE".equals(result)) {
			Boot.state().remove(State.NO_REPEAT_NO_PLAYLIST);
			Boot.state().remove(State.REPEAT_ONE_TUNE);
			Boot.state().add(State.PLAYLIST_MODE);
		} else if ("NO_REPEAT_NO_PLAYLIST".equals(result)) {
			Boot.state().remove(State.PLAYLIST_MODE);
			Boot.state().remove(State.REPEAT_ONE_TUNE);
			Boot.state().add(State.NO_REPEAT_NO_PLAYLIST);
		}
	}
}
